package com.gree.syq.wifidemo;

import android.content.Context;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;


public class MessageP2P {
    private final static String TAG = "MessageP2P";

    private Context mContext;
    private static MessageP2P sMessageP2P = null;
    private static WifiP2pManager manager = null;
    private static WifiP2pManager.Channel channel;
    private static String mMesg;
    private HandlerThread mMessageThread;
    private static Handler mMessageHandler;


    public final static int COMMAND = 0;
    public final static int REFRESH = 1;
    public final static int CONFIG_NETWORK = 2;
    public final static int DEVICE_STATE = 3;
    public final static int KEEP = 4;

    private final static int SEND_COUNT = 80;

    private Runnable keepRun = new Runnable() {
        @Override
        public void run() {
            keepSendMessage("KEEP",null);
            mMessageHandler.postDelayed(this,3000);
        }
    };

    public static MessageP2P getInstance(Context context) {
        if(sMessageP2P == null) {
            sMessageP2P = new MessageP2P(context);
        }
        return sMessageP2P;
    }

    public void onCreate () {
        if(sMessageP2P != null) {
            mMessageHandler.post(keepRun);
        }
    }

    protected MessageP2P(Context context) {
        mContext = context;
        manager = (WifiP2pManager) context.getSystemService(Context.WIFI_P2P_SERVICE);
        channel = manager.initialize(context, context.getMainLooper(), null);
        mMessageThread = new HandlerThread("process message");
        mMessageThread.start();
        mMessageHandler = new Handler(mMessageThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case COMMAND:
                    case REFRESH:
                        //DemoLog.getInstance().logi("探测设备开始:" + msg.what);
                        messageProcess(msg);
                        break;
                    case CONFIG_NETWORK:
                        //DemoLog.getInstance().logi("配网开始:" + msg.what);
                        messageProcess(msg);
                        break;
                    case DEVICE_STATE:
                        if(msg.getData().getInt("count",0) == SEND_COUNT) {
                            removeMessages(DEVICE_STATE);
                        }
                        //DemoLog.getInstance().logi("回传状态开始:" + msg.what);
                        messageProcess(msg);
                        break;
                    default:
                        break;
                }
            }

            private void messageProcess (Message msg) {
                if(msg.getData().getInt("count",0) > 0) {
                    //removeCallbacks(keepRun);
                    MessageP2P.getInstance(mContext).innerSendMessage(msg.getData().getString("command"), null);
                    sendCommand(msg.getData().getString("command"),msg.what,msg.getData().getInt("count",0) - 1);
                    //MessageP2P.getInstance(mContext).innerSendMessage("1234567",null);
                } else {
                    //DemoLog.getInstance().logi("指令结束:" + msg.what);
                    post(keepRun);
                    //keepSendMessage("KEEP",null);
                }
            }
        };
    }


    public void keepSendMessage(String msg , final WifiP2pManager.ActionListener actionListener) {
        if(manager !=null) {

            manager.p2pFlush(channel, null);
            manager.setDeviceName(channel,
                    msg,
                    new WifiP2pManager.ActionListener() {
                        public void onSuccess() {
                            Log.d(TAG, " device rename success");
                            manager.discoverPeers(channel,actionListener);
                        }
                        public void onFailure(int reason) {
                            Log.d(TAG, " device rename failed");
                        }
                    });

        }
    }

    public void innerSendMessage(String msg , final WifiP2pManager.ActionListener actionListener) {
        if(manager !=null) {

            manager.p2pFlush(channel, null);
            manager.setDeviceName(channel,
                    msg,
                    new WifiP2pManager.ActionListener() {
                        public void onSuccess() {
                            Log.d(TAG, " device rename success");
                            manager.discoverPeers(channel,actionListener);
                        }
                        public void onFailure(int reason) {
                        Log.d(TAG, " device rename failed");
                    }
                    });
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    public static void unRegister() {

        mMessageHandler.postAtFrontOfQueue(new Runnable() {
            @Override
            public void run() {
                mMessageHandler.removeCallbacksAndMessages(null);
                if(manager !=null) {
                    manager.stopPeerDiscovery(channel, null);
                }
            }
        });
    }

    private void sendCommand(String cmd, int what) {
        manager.p2pFlush(channel, null);
        sendCommand(cmd,what, SEND_COUNT);
    }

    private void sendCommand(String cmd,int what, int count) {
        Message msg = new Message();
        msg.what = what;
        Bundle bundle = new Bundle();
        bundle.putString("command",cmd);
        bundle.putInt("count",count);
        msg.setData(bundle);
        mMessageHandler.sendMessage(msg);
    }

    public void clearDeviceStateCommand() {
        mMessageHandler.removeMessages(DEVICE_STATE);
    }

    public native void sendRefreshCommand();
    public native void sendNetworkCommand(String ssid,String pwd,int mode);
    public native void sendDeviceStateCommand(int state,int addr);
}
